// 全局变量
let currentUser = null;
let ws = null;

// 工具函数
function getToken() {
    return localStorage.getItem('token');
}

function formatTime(date) {
    if (typeof date === 'string') {
        date = new Date(date);
    }
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

// WebSocket连接
function connectWebSocket() {
    const token = getToken();
    if (!token) return;

    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/api/v1/ws?token=${token}`;
    
    ws = new WebSocket(wsUrl);

    ws.onmessage = function(event) {
        const data = JSON.parse(event.data);
        handleWebSocketMessage(data);
    };

    ws.onclose = function() {
        setTimeout(connectWebSocket, 3000); // 断线重连
    };
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    if (data.type === 0) { // TextMessage
        appendMessage({
            from_user_id: data.from,
            content: data.content,
            CreatedAt: data.timestamp, // 使用CreatedAt字段名
            sender_name: data.sender_name
        });
    } else if (data.type === 1) { // SystemMessage
        appendSystemMessage(data.content);
    }
}

// 获取当前用户信息
async function getCurrentUser() {
    try {
        const response = await fetch('/api/v1/user', {
            headers: {
                'Authorization': `Bearer ${getToken()}`
            }
        });
        const data = await response.json();
        if (response.ok) {
            currentUser = data.data;
            updateCurrentUserInfo();
        } else {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        window.location.href = '/login';
    }
}

// 获取用户列表
async function getUsers() {
    try {
        const response = await fetch('/api/v1/users', {
            headers: {
                'Authorization': `Bearer ${getToken()}`
            }
        });
        const data = await response.json();
        if (response.ok) {
            updateUserList(data.data);
        }
    } catch (error) {
        console.error('获取用户列表失败:', error);
    }
}

// 获取历史消息
async function getMessages() {
    try {
        const response = await fetch('/api/v1/messages', {
            headers: {
                'Authorization': `Bearer ${getToken()}`
            }
        });
        const data = await response.json();
        if (response.ok) {
            updateMessageList(data.data);
        }
    } catch (error) {
        console.error('获取消息失败:', error);
    }
}

// 更新当前用户信息
function updateCurrentUserInfo() {
    const name = document.getElementById('currentUserName');
    name.textContent = currentUser.nickname || currentUser.username;
}

// 更新用户列表
function updateUserList(users) {
    const userList = document.getElementById('userList');
    const template = document.getElementById('userItemTemplate');
    userList.innerHTML = '';

    users.forEach(user => {
        if (user.id === currentUser.id) return; // 不显示当前用户

        const clone = template.content.cloneNode(true);
        const userItem = clone.querySelector('.user-item');
        const avatar = clone.querySelector('img');
        const name = clone.querySelector('h6');
        const status = clone.querySelector('small');

        userItem.dataset.userId = user.id;
        avatar.src = user.avatar || '/static/img/default-avatar.png';
        name.textContent = user.nickname || user.username;
        status.textContent = user.online ? '在线' : '离线';
        status.className = `text-${user.online ? 'success' : 'muted'}`;

        userList.appendChild(clone);
    });
}

// 更新消息列表
function updateMessageList(messages) {
    const messageList = document.getElementById('messageList');
    messageList.innerHTML = '';

    messages.reverse().forEach(message => {
        appendMessage(message);
    });
}

// 添加消息
function appendMessage(message) {
    const messageList = document.getElementById('messageList');
    const template = document.getElementById('messageTemplate');
    const clone = template.content.cloneNode(true);
    const messageDiv = clone.querySelector('.message');
    const name = clone.querySelector('.fw-bold');
    const time = clone.querySelector('.text-muted');
    const content = clone.querySelector('.message-content');

    const isSent = message.from_user_id === currentUser.id;
    if (isSent) {
        messageDiv.classList.add('sent');
    }

    // 使用服务器返回的发送者名称
    const senderName = isSent ? (currentUser.nickname || currentUser.username) : 
        (message.sender_name || '未知用户');

    name.textContent = senderName;
    time.textContent = formatTime(message.CreatedAt);
    content.textContent = message.content;

    messageList.appendChild(clone);
    messageList.scrollTop = messageList.scrollHeight;
}

// 添加系统消息
function appendSystemMessage(content) {
    const messageList = document.getElementById('messageList');
    const div = document.createElement('div');
    div.className = 'text-center text-muted small my-2';
    div.textContent = content;
    messageList.appendChild(div);
    messageList.scrollTop = messageList.scrollHeight;
}

// 发送消息
function sendMessage(content) {
    if (!ws || ws.readyState !== WebSocket.OPEN) {
        alert('WebSocket连接已断开，请刷新页面重试');
        return;
    }

    const message = {
        type: 0, // TextMessage
        content: content
    };

    ws.send(JSON.stringify(message));
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
    // 获取当前用户信息
    await getCurrentUser();

    // 获取用户列表
    await getUsers();

    // 获取历史消息
    await getMessages();

    // 连接WebSocket
    connectWebSocket();

    // 消息表单提交
    const messageForm = document.getElementById('messageForm');
    const messageInput = document.getElementById('messageInput');

    messageForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const content = messageInput.value.trim();
        if (content) {
            sendMessage(content);
            messageInput.value = '';
        }
    });

    // 登出按钮
    document.getElementById('logoutBtn').addEventListener('click', async function() {
        try {
            await fetch('/api/v1/logout', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            });
            localStorage.removeItem('token');
            window.location.href = '/login';
        } catch (error) {
            console.error('登出失败:', error);
        }
    });
}); 